import { PDFDocumentLoadingTask } from "pdfjs-dist/types/src/display/api";
import {ImageUtils} from "@/utils/ImageUtils";
import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf'
// @ts-ignore
pdfjsLib.GlobalWorkerOptions.workerSrc = await import('pdfjs-dist/build/pdf.worker.entry')
// Some PDFs need external cmaps.
const CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/";
const CMAP_PACKED = true;

// Where the standard fonts are located.
const STANDARD_FONT_DATA_URL = "../../node_modules/pdfjs-dist/standard_fonts/";

export class FileUtils {

    static createLoadingTask(pdfUrl: string): PDFDocumentLoadingTask {
        //console.log("# PDF document loading.");
        // Load the PDF file.
        return pdfjsLib.getDocument(pdfUrl);
        // return createLoadingTask0(pdfUrl);
    }
    static async toImageArray(loadingTask: PDFDocumentLoadingTask, imageCanvasArray: any, imageUrlArray: any) {

       await (async function () {
            try {
                console.log("# PDF document loading.");
                const pdfDocument = await loadingTask.promise;
                console.log("# PDF document loaded.");
                // Get the first page.
                const numOfPages = pdfDocument.numPages;
                for (let i=1; i<numOfPages + 1; ++i) {
                    let canvas = document.createElement('canvas');
                    let ctx = canvas.getContext('2d') as any;
                    const pageProxy = await pdfDocument.getPage(i);
                    // Render the page on a Node canvas with 100% scale.
                    const viewport = pageProxy.getViewport({ scale: 3.0 });
                    let dpr = window.devicePixelRatio || 1
                    let bsr = ctx.webkitBackingStorePixelRatio ||
                        ctx.mozBackingStorePixelRatio ||
                        ctx.msBackingStorePixelRatio ||
                        ctx.oBackingStorePixelRatio ||
                        ctx.backingStorePixelRatio || 1
                    let ratio = dpr / bsr
                    canvas.width = viewport.width * ratio
                    canvas.height = viewport.height * ratio
                    canvas.style.width = viewport.width + 'px'
                    canvas.style.height = viewport.height + 'px'
                    const renderContext = {
                        canvasContext: ctx,
                        viewport,
                    };
                    const renderTask = pageProxy.render(renderContext);
                    await renderTask.promise;
                    // Convert the canvas to an image buffer.
                    //imageBufferArray.push(canvas.toBuffer());
                    imageCanvasArray.push(canvas);
                    const base64Data = canvas.toDataURL("image/png");
                    imageUrlArray.push(URL.createObjectURL(ImageUtils.base64ToBlob(base64Data, 'image/png')));
                    // Release page resources.
                    pageProxy.cleanup();
                    console.log(imageUrlArray);
                }
            } catch (reason) {
                console.log(reason);
            }
        })();
    }

    /**
     * png|jpg|gif|jpeg|webp|bmp|x-ms-bmp|psd|svg|tiff|ico
     * 判断文件明是否是图片
     * @param filePath
     */
    static isImage(filePath: string) : boolean {
        const index = filePath.lastIndexOf('.');
        const ext = filePath.substr(index + 1);
        return [
            'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff', 'ico', 'x-ms-bmp']
            .indexOf(ext.toLowerCase()) !== -1
    }

    /**
     * pdf/PDF/ofd/OFD
     * 判断文件明是否是PDF
     * @param filePath
     */
    static isPdf(filePath: string) : boolean {
        const index = filePath.lastIndexOf('.');
        const ext = filePath.substr(index + 1);
        return [
            'pdf', 'PDF', 'ofd', 'OFD']
            .indexOf(ext.toLowerCase()) !== -1
    }

    /**
     * 判断是不是文本文件
     * @param filePath
     */
    static isText(filePath: string): boolean {
        const index = filePath.lastIndexOf('.');
        const ext = filePath.substr(index + 1);
        return [
            'txt', 'TXT', 'json', 'js', 'css', 'java', 'py', 'html', 'jsx', 'ts', 'tsx', 'xml', 'md', 'log']
            .indexOf(ext.toLowerCase()) !== -1
    }
}